package com.imooc.security.browser.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.security.core.properties.LoginyType;
import com.imooc.security.core.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义登陆成功处理器。将Authentication对象信息json格式发送到客户端
 * @author JackYang
 * @description:
 * @create: 2020/6/15 16:56
 */
@Component(value = "imoocAuthenticationSuccessHandler")
public class ImoocAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    
    Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private SecurityProperties securityProperties;
    
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        logger.info("登陆成功了........");
        if (LoginyType.JSON.equals(securityProperties.getBrowser().getLoginyType())){
            response.setContentType("application/json;charset=UTF-8");
            //以json格式输出authentication对象信息
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        }else {
            //调用SpringSecurity默认的登录成功处理器
            super.onAuthenticationSuccess(request,response,authentication);
        }
        
    }
}
